package com.xongxong.admin.service.impl;


import cn.hutool.http.server.HttpServerRequest;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.cache.Cache;
import com.xongxong.admin.common.constants.Constants;
import com.xongxong.admin.mapper.UserInfoMapper;
import com.xongxong.admin.service.CodeService;
import com.xongxong.admin.service.UserInfoService;
import com.xongxong.admin.utils.threadLocalUtils.UserIdUtils;
import com.xongxong.domain.entity.UserInfo;
import com.xongxong.domain.req.loginReq;
import com.xongxong.domain.vo.userVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.UUID;


/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author dxx
 * @since 2024-12-01
 */
@Slf4j
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private CodeService codeService;

    @Resource
    private Cache<String, userVo> userInfoCache;
    @Override
    public userVo login(loginReq loginReq) {
        String codeKey = loginReq.getCodeKey();
        String codeValue = loginReq.getCodeValue();
        if (StringUtils.isEmpty(loginReq.getUsername()) || StringUtils.isEmpty(loginReq.getPassword())||StringUtils.isEmpty(codeKey)||StringUtils.isEmpty(codeValue)) {
            throw new RuntimeException("参数异常");
        }
        // 校验-验证码是否正确
        boolean captcha = codeService.captcha(codeKey, codeValue);
        if (!captcha) {
            throw new RuntimeException("验证码有误请重新输入!");
        }
        userVo user = userInfoMapper.login(loginReq);
        if (ObjectUtils.isEmpty(user)) {
            throw new RuntimeException("登入失败");
        }
        UUID uuid = UUID.randomUUID();
        String replace = uuid.toString().replace("-", "");
        String token=replace+":"+ user.getId();
        log.info("生成的token:{}",token);
        user.setToken(token);
        return user;
    }

    @Override
    public String logout() {
        userVo userVo = UserIdUtils.get();
        userInfoCache.invalidate(Constants.CachStatusEnum.EASY_ADMIN_TOKEN+":"+userVo.getId());
        return "退出登入成功";
    }


}
